<template>
  <div class="editor-wrapper">
    <div :id="editorId"></div>
  </div>
</template>

<script>
import Editor from 'wangeditor'
import 'wangeditor/release/wangEditor.min.css'
import { oneOf } from '@/libs/tools'
import * as qiniu from 'qiniu-js'
export default {
  name: 'Editor',
  props: {
    value: {
      type: String,
      default: ''
    },
    /**
     * 绑定的值的类型, enum: ['html', 'text']
     */
    valueType: {
      type: String,
      default: 'html',
      validator: (val) => {
        return oneOf(val, ['html', 'text'])
      }
    },
    /**
     * @description 设置change事件触发时间间隔
     */
    changeInterval: {
      type: Number,
      default: 200
    },
    /**
     * @description 是否开启本地存储
     */
    cache: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    editorId () {
      return `editor${this._uid}`
    }
  },
  methods: {
    setHtml (val) {
      this.editor.txt.html(val)
    },
    uploadInit (blob) {
      // 创建上传对象
      return new Promise((resolve, reject) => {
        this.jsonrpc.blind.admin.getTokenToUpload().then((res, err) => {
          if (err) {
            reject(err)
          } else {
            let observable = qiniu.upload(blob, res.key, res.token, {
              fname: res.key,
              params: {},
              mimeType: null
            }, {
              useCdnDomain: true,
              region: qiniu.region.z0,
              checkByMD5: true
            })
            observable.subscribe({
              next: () => {},
              error: (err) => {
                reject(err)
              },
              complete: (result) => {
                resolve(res.domain + '/' + result.key)
              }
            })
          }
        })
      })
    }
  },
  mounted () {
    this.editor = new Editor(`#${this.editorId}`)
    this.editor.customConfig.onchange = (html) => {
      let text = this.editor.txt.text()
      if (this.cache) localStorage.editorCache = html
      this.$emit('input', this.valueType === 'html' ? html : text)
      console.log(this.valueType)
      this.$emit('on-change', html, text)
    }
    this.editor.customConfig.menus = [
      'head', // 标题
      'bold', // 粗体
      'fontSize', // 字号
      'fontName', // 字体
      'italic', // 斜体
      'underline', // 下划线
      'strikeThrough', // 删除线
      'foreColor', // 文字颜色
      'link', // 插入链接
      'list', // 列表
      'justify', // 对齐方式
      'image', // 插入图片
      'table', // 表格
      'undo', // 撤销
      'redo' // 重复
    ]

    this.editor.customConfig.onchangeTimeout = this.changeInterval
    // 上传图片
    this.editor.customConfig.customUploadImg = (files, insert) => {

      function base64ToBlob(dataurl) {
        let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        return new Blob([u8arr], { type: mime })
      }

      this.$Loading.start()
      files.forEach((item) => {
        console.log(item)
        const reader = new FileReader();
        reader.readAsDataURL(item);
        reader.onload = async (e) => {
          const blobData = base64ToBlob(event.srcElement.result)
          const url = await this.uploadInit(blobData)
          insert(url)
        }
      })
      this.$Loading.finish()
    };
    // create这个方法一定要在所有配置项之后调用
    this.editor.create()
    // 如果本地有存储加载本地存储内容
    let html = this.value || localStorage.editorCache
    if (html) this.editor.txt.html(html)
  }
}
</script>

<style lang="less">
.editor-wrapper *{
  z-index: 100 !important;
}
</style>
